<template>
  <!-- 根据条件从后端返回数据 -->
  <el-form ref="big_form" :label-position=" 'right' " label-width="90px"
           :inline="true">
    <el-form-item prop="use" label="启用状态">
      <el-radio-group v-model="material_group_use">
        <el-radio-button value="enable">启用</el-radio-button>
        <el-radio-button value="not_enable">未启用</el-radio-button>
        <el-radio-button value="all">全部</el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="return_material_group_list()">搜索</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="return_small_list()">导出表格</el-button>
    </el-form-item>
    <el-form-item>
      <el-button @click=" handleAdd() ">添加物料分组</el-button>
    </el-form-item>
  </el-form>

  <!-- 表格数据显示区域 -->
  <!-- 这建立在id唯一的情况下 -->
  <el-table :data="material_group_list" style="width: 100%" row-key="id" id="table5_id">
    <!--选择框-->
    <el-table-column label="物料编码ID" prop="id"/>
    <el-table-column label="物料分组名称" prop="name"/>
    <el-table-column label="助记码" prop="mnemonic"/>
    <el-table-column label="是否启用">
      <template #default="scope">
        <el-switch v-model="scope.row.enable" size="small" @click="switch_change(scope.row)"/>
      </template>
    </el-table-column>
    <el-table-column label="操作人" prop="operator__username"/>
    <el-table-column label="操作日期" prop="operate_date_"/>
    <el-table-column label="正品实际重量/吨" prop="weight"/>
    <el-table-column label="正品理论重量/克" prop="theory_weight"/>
    <el-table-column label="次品实际重量/吨" prop="disable_weight"/>
    <el-table-column label="次品理论重量/克" prop="disable_theory_weight"/>
    <el-table-column label="正品重量调整/吨" prop="weight_fix"/>
    <el-table-column label="次品重量调整/吨" prop="disable_weight_fix"/>
    <el-table-column align="right">
      <template #header></template>
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
        >删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[100, 200, 500]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total=" total "
  />

  <!--添加/修改物料分组-->
  <el-dialog v-model="add_or_update_form_visible"
             :title=" add_or_update_material_group_signal "
             :close-on-click-modal='false'
             :close-on-press-escape='false'
             :show-close='false'>

    <el-form :model="add_or_update_material_group_variable" :rules="add_or_update_material_group_rules" ref="add_or_update_form_ref" :label-position=" 'right' " label-width="90px">
      <!-- :rules="rules" -->
      <el-form-item prop="name" label="分组名称">
        <el-input v-model="add_or_update_material_group_variable.name" autocomplete="off"/>
      </el-form-item>

      <el-form-item prop="mnemonic" label="助记码">
        <el-input v-model="add_or_update_material_group_variable.mnemonic" autocomplete="off"/>
      </el-form-item>

      <el-form-item prop="weight_fix" label="正品重量调整">
        <el-input-number v-model="add_or_update_material_group_variable.weight_fix" autocomplete="off" :min="0" :step="0.001" step-strictly />
      </el-form-item>

      <el-form-item prop="weight_fix" label="次品重量调整">
        <el-input-number v-model="add_or_update_material_group_variable.disable_weight_fix" autocomplete="off" :min="0" :step="0.001" step-strictly />
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel(big_form)">取消</el-button>
        <el-button type="primary" @click="add_or_update_material_group(big_form)">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  MaterialGroupFuzzySearchResp,
  MaterialGroupList
} from '@/api/inventory/material_group/type.ts'
import {reactive, ref, watch} from 'vue'
import type {FormInstance} from 'element-plus'
import {ElMessage, FormRules} from "element-plus";
import {make_excel_file} from '@/hooks/make_excel_file.ts'
import {
  req_material_group_create,
  req_material_group_deactivation_and_activation,
  req_material_group_delete,
  req_material_group_fuzzy_search, req_material_group_update,
} from "@/api/inventory/material_group";
import {MaterialGroupCRUDResp, MaterialGroupUseResp} from "@/api/inventory/material_group/type.ts";

const return_small_list = () => {
  make_excel_file('库存检查表', 'table5_id')
}

// 大类表所需要的变量和函数
const big_form = ref<FormInstance>() // big表检索条件表单的ref

const material_group_list = ref<MaterialGroupList[]>([]) // big表的数据
const material_group_use = ref<'enable' | 'not_enable' | 'all'>('enable') // 需要传回后端的内容

// 分页
const background = ref<boolean>(true)  // 是否带背景方框
const disabled = ref<boolean>(false)  // 是否可用
const small = ref<boolean>(false)  // 普通大小还是小一号
const currentPage = ref<number>(1)  // 当前所在页数
const pageSize = ref<number>(100)  // 一页有几条记录
const total = ref<number>(0) // 总条数

// 同时监视所在页数和一页有几条记录两者的变化
watch([currentPage, pageSize], () => {
  return_material_group_list()
})

// 添加或修改大类零件
const add_or_update_form_ref = ref<FormInstance>()
const add_or_update_material_group_signal = ref<string>('')  // 取值为 添加 或者 修改
const add_or_update_form_visible = ref<boolean>(false)  // 控制大类表的添加或删除弹框是否出现


const add_or_update_material_group_rules = reactive<FormRules>({
  name: [{
    type: 'string',
    message: '分组名称应小于等于100个字符',
    max: 100,
    min: 1,
    required: true
  }],
  mnemonic: [{
    type: 'string',
    message: '助记码应小于等于100个字符',
    max: 100,
    min: 1,
    required: true
  }],
})

const add_or_update_material_group_variable = reactive<{
  id: number | null,
  mnemonic: string,
  name: string,
  index: number | null
  weight_fix: number | null
  disable_weight_fix: number | null
}>({
  id: null,
  name: '',
  mnemonic: '',
  index: null,
  weight_fix: 0,
  disable_weight_fix: 0,
})

// 弹出添加框并准备框中的内容
const handleAdd = () => {
  add_or_update_form_visible.value = true
  add_or_update_material_group_signal.value = '添加物料分类'
  add_or_update_material_group_variable.name = ''
  add_or_update_material_group_variable.mnemonic = ''
  add_or_update_form_ref.value?.clearValidate()
}

// 弹出修改框并准备框中的内容
const handleEdit = (index: number, row: MaterialGroupList) => {
  add_or_update_form_visible.value = true
  add_or_update_material_group_signal.value = '修改物料分类'
  add_or_update_material_group_variable.id = row.id
  add_or_update_material_group_variable.name = row.name
  add_or_update_material_group_variable.mnemonic = row.mnemonic
  add_or_update_material_group_variable.index = index
  add_or_update_form_ref.value?.clearValidate()
}

const cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()  // 清除表格的错误提示
  add_or_update_form_visible.value = false
}

// 点击添加框中的确认，执行添加
const add_or_update_material_group = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await add_or_update_form_ref.value?.validate()
  add_or_update_form_visible.value = false
  if (add_or_update_material_group_signal.value === '添加物料分类') {
    const result: MaterialGroupCRUDResp<'create'> = await req_material_group_create({
      mode: 'create',
      param: {
        name: add_or_update_material_group_variable.name,
        mnemonic: add_or_update_material_group_variable.mnemonic
      },
    })
    ElMessage.success(result.success?.message)
  } else {
    const result: MaterialGroupCRUDResp<'update'> = await req_material_group_update({
      mode: 'update',
      param: {
        id: add_or_update_material_group_variable.id as number,
        name: add_or_update_material_group_variable.name,
        mnemonic: add_or_update_material_group_variable.mnemonic,
        weight_fix: add_or_update_material_group_variable.weight_fix as number,
        disable_weight_fix: add_or_update_material_group_variable.disable_weight_fix as number,
      },
    })
    let temp = material_group_list.value[add_or_update_material_group_variable.index as number]
    temp.name = add_or_update_material_group_variable.name
    temp.mnemonic = add_or_update_material_group_variable.mnemonic
    ElMessage.success(result.success?.message)
  }
}


const return_material_group_list = () => {
  req_material_group_fuzzy_search({
      enable: material_group_use.value,
      mnemonic: null,
      name: null,
      start: (currentPage.value - 1) * pageSize.value,
      stop: currentPage.value * pageSize.value,
  }).then((res: MaterialGroupFuzzySearchResp) => {
    material_group_list.value = res.data.result as MaterialGroupList[]
    total.value = res.data.total as number
    ElMessage.success(res.success?.message)
  })
}

// 通过switch修改使用情况
const switch_change = async(row: MaterialGroupList) => {
  const result: MaterialGroupUseResp = await req_material_group_deactivation_and_activation({
      id: row.id
  }).catch(() => {
    // 修改被拒绝，现场恢复原状
    row.enable = !row.enable
  })
  ElMessage.success(result.success?.message)
}

// 删除
const handleDelete = async (index: number, row: MaterialGroupList) => {
  if(row.enable){
    ElMessage.warning('该物料分类尚未停止使用')
    return
  }
  const result: MaterialGroupCRUDResp<'delete'> = await req_material_group_delete({
    mode: 'delete',
    param: {
      id: row.id,
    }
  })
  material_group_list.value.splice(index, 1)
  ElMessage.success(result.success?.message)
}
</script>

<style scoped>

</style>